import Vue from 'vue'


const utils = {
    getDomain() {
        let _domain='';
        if (process.env.NODE_ENV == 'development') {
            _domain = "http://machine.mgmcbx.com";
			//_domain = "http://machine_vue.mgmcbx.com"; 
        } else {
            _domain = "http://machine.mgmcbx.com";         
        }
          
        console.log("_domain==", _domain);
        return _domain;
    },

    getbaseurl() {       
        let  _web =  this.getDomain()+"/index.php/api";        
        console.log("web==", _web);
        return _web;
    },

    // 手机号格式是否正确
    isMobilePhone(value) {
        const reg = /^1\d{10}$/
        if (reg.test(value)) {
            return true
        }
        return false
    },

    ById(_E) {
        return document.getElementById(_E);
    },



    queryByClass(eL) {
        return document.getElementsByClassName(eL)
    },

    querySelector(eL) {
        return document.querySelector(eL); //取一个
        //https://www.cnblogs.com/jianjie/p/12163942.html
    },

    querySelectorAll(eL) {
        return document.querySelectorAll(eL); //取所有的
        //https://www.cnblogs.com/jianjie/p/12163942.html
    },

    querySelectName(name) {
        //input name="telephone" value="1111"  
        return document.getElementsByName(name)[0].value;
    },

    getRadiosCheckValue(name) {
        //<input name="buytypes" value="1" type="radio" checked >
        //<input name="buytypes" value="2" type="radio"  />
        var radios = document.getElementsByName("buytypes");
        var value = 0;
        for (var i = 0; i < radios.length; i++) {
            if (radios[i].checked == true) {
                value = radios[i].value;
            }
        }
        return value;
    },

    getSelectOption() {

    },

    addCalssName(eL, classname) {
        eL.classList.add(classname)
    },

    removeCalssName(eL, classname) {
        eL.classList.remove(classname)
    },

    addAttribute(eL, AttributeName, AttributeVal) {
        eL.setAttribute(AttributeName, AttributeVal)
    },

    removeAttribute(eL, AttributeName) {
        eL.removeAttribute(AttributeName);
    },

    //加
    floatAdd(arg1, arg2) {
        var r1, r2, m;
        try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
        try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
        m = Math.pow(10, Math.max(r1, r2));
        return (arg1 * m + arg2 * m) / m;
    },

    //减    
    floatSub(arg1, arg2) {
        var r1, r2, m, n;
        try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
        try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
        m = Math.pow(10, Math.max(r1, r2));
        //动态控制精度长度    
        n = (r1 >= r2) ? r1 : r2;
        return ((arg1 * m - arg2 * m) / m).toFixed(n);
    },

    //乘    
    floatMul(arg1, arg2) {
        var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
        try { m += s1.split(".")[1].length } catch (e) { }
        try { m += s2.split(".")[1].length } catch (e) { }
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    },


    //除   
    floatDiv(arg1, arg2) {
        var t1 = 0, t2 = 0, r1, r2;
        try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
        try { t2 = arg2.toString().split(".")[1].length } catch (e) { }

        r1 = Number(arg1.toString().replace(".", ""));

        r2 = Number(arg2.toString().replace(".", ""));
        return (r1 / r2) * Math.pow(10, t2 - t1);
    },

    //一个汉字相当于2个字符
    get_length(s) {
        var char_length = 0;
        for (var i = 0; i < s.length; i++) {
            var son_char = s.charAt(i);
            encodeURI(son_char).length > 2 ? char_length += 1 : char_length += 0.5;
        }
        return char_length;
    },
      //  截取15个字（30个字符）
    //  cut_str('aa啊啊啊啊啊啊啊啊啊啊啊啊啊k的啊是', 15);
    cut_str(str, len) {
        var char_length = 0;
        for (var i = 0; i < str.length; i++) {
            var son_str = str.charAt(i);
            encodeURI(son_str).length > 2 ? char_length += 1 : char_length += 0.5;
            if (char_length >= len) {
                var sub_len = char_length == len ? i + 1 : i;
                return str.substr(0, sub_len);
                break;
            }
        }
    },

    //uni.redirectTo(OBJECT)
    gotopage: function (url, model = 'redirectTo') {

        if (model == 'navigateTo') {
            /* 保留当前页面，跳转到应用内的某个页面 */
            uni.navigateTo({
                url: url
            });
        }
        if (model == 'redirectTo') {
            //关闭当前页面，跳转到应用内的某个页面
            uni.redirectTo({
                //url: '/pages/index/index'
                url: url
            });
        }
        if (model == 'reLaunch') {
            //关闭所有页面，打开到应用内的某个页面
            uni.reLaunch({
                url: url
            });
        }
    },
    gotohome: function () {
        uni.reLaunch({
            url: '/'
        })
    },
    /* 提示提交成功并转向 */
    successGotoUrl(url, title = '') {
        uni.showToast({
            title: title || '成功提交',
            icon: 'success',
            duration: 300
        });
        if (url=='reload') {
             setTimeout(() => {
                 location.reload() 
            }, 300);
        }
        if (url=='back') {
            setTimeout(() => {
                history.back();
            }, 300);
        } else {
            setTimeout(() => {
                uni.redirectTo({
                    url: url
                });
                return false;
            }, 300);
        }
    },
    isLoginGotoPage() {
        let token = this.getStorage('token');
        if (!token) {
            uni.showToast({
                title: 'token不能为空',
                icon: 'success',
                duration: 800
            });

            setTimeout(() => {
                uni.reLaunch({
                    url: '/'
                });
                return false;
            }, 300);
        }
    },

    /* getQueryVariable费掉
        替代
        onLoad(param) {           
            this.param = param;
        },
     */
     
    getQueryVariable(variable = false) {
        let query = document.location.href;
        if (query == '') {
            return false;
        }
 
        let vars = query.split("?");
        let correspond = null;
        let p = [];
        for (let i = 0; i < vars.length; i++) {
            let pair = vars[i].split("=");
            if (variable != false) {
                if (pair[0] == variable) {
                    correspond = pair[1];
                }
            }
            p[pair[0]] = decodeURIComponent(pair[1]);
        }

        if (variable) {
            return correspond;
        }

        if (vars.length == 0) return false;

        return p;
    },

    saveStorage(name, val) {
        // if (!window.localStorage) {
        //     alert("浏览器不支持localstorage");
        //     return false;
        // } else {
        //     var storage = window.localStorage;
        //     if (name == '' || false == name || name == null) {
        //         return false;
        //     }
        //     if (false == val || val == null) {
        //         storage.removeItem(name);
        //         return false;
        //     }

        //     //写入a字段
        //     storage[name] = val;
        // }
 
        uni.setStorageSync(name, val);
    },

    getStorage(name) {
        // if (!window.localStorage) {
        //     alert("浏览器不支持localstorage");
        //     return false;
        // } else {
        //     var storage = window.localStorage;
        //     //写入a字段
        //     return storage[name] ? storage[name] : false;
        // }

        return uni.getStorageSync(name);
    },



    myRequest(option) {
        let token = this.getStorage('token');

        return new Promise((resolve, reject) => {
            uni.request({
                url: option.fullurl || (this.getbaseurl() + option.url),
                method: option.method || 'GET',
                data: option.data || {},
                header: { 'Authorization': token ? token : '' },
                dataType: 'json',
                timeout: 30 * 1000,
                success: (res) => {
                    if (res.data.status==101) {
                        uni.showToast({
                            title: 'token失效' || res.data.msg,
                            icon: 'loading',
                            duration: 500
                        });
            
                        setTimeout(() => {
                            uni.reLaunch({
                                url: '/'
                            });
                            return false;
                        }, 500);
                        return false;
                    }
                    if (res.data.status != 200) {
                        return uni.showToast({
                            title: res.data.msg || '获取数据失败'
                        });
                    }

                    resolve(res)
                },
                fail: (err) => {

                    uni.showToast({
                        title: '请求接口失败'
                    });
                    reject(err)
                }
            });
        })
    }

}

Vue.prototype.$utils = utils

export default utils